package com.marketingexpert.controller.marketingmgnt.activityrecomment;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.marketingexpert.config.SystemErrorCode;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.marketingmgnt.MarketingService;
import com.marketingexpert.service.storemgnt.MarketingPromotion;
import com.marketingexpert.util.Resources;
import com.marketingexpert.util.WebUtils;

public class QueryItemPromotionController implements Controller {

	private MarketingService marketingService;	
	
	private SystemErrorCode systemErrorCode;
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		long proPageNo = 1L;
		
		String dispatchUrl = request.getParameter("dispatchUrl");
		String sessionKey = (String) request.getSession().getAttribute("taobaoSessionKey");
		String[] itemIds = request.getParameterValues("itemId");
		
		
		String promotionPageNoParam = request.getParameter("promotionPageNo");
		
		if(promotionPageNoParam != null && !promotionPageNoParam.equals("")) {
			proPageNo = Long.parseLong(promotionPageNoParam);
		}
		
		try {
			request.setAttribute("pageNo", request.getParameter("pageNo"));
			request.setAttribute("forwordUrl", request.getParameter("forwordUrl"));
			List<MarketingPromotion> promotions = marketingService.batchGetItemPromotion(itemIds,sessionKey,proPageNo);			
			if(promotions == null || promotions.size() == 0) {
				return new ModelAndView(dispatchUrl, "promotions", null);	
			}
			return new ModelAndView(dispatchUrl, "promotions", promotions);		
		} catch(MarketingExpertException e) {
			if(e.getErrCode().equals(systemErrorCode.getInvalidSession()) || e.getErrCode().equals(systemErrorCode.getTaobaoExpiredSession())) {
				request.getSession().removeAttribute("taobaoSessionKey");
				request.getSession().removeAttribute("parentUserId");
				request.getSession().setAttribute("sessionExpired", Resources.getString("InvalidSession"));
				response.sendRedirect(WebUtils.getBasepath(request) + "/pages/sessionExpiredTip.jsp");
				return null;
			}
			request.setAttribute("queryPromotionFailed",Resources.getString("QueryItemPromotionController.queryPromotionFailed"));
			return new ModelAndView(dispatchUrl);
		}	
	}

	public MarketingService getMarketingService() {
		return marketingService;
	}

	public void setMarketingService(MarketingService marketingService) {
		this.marketingService = marketingService;
	}

	public SystemErrorCode getSystemErrorCode() {
		return systemErrorCode;
	}

	public void setSystemErrorCode(SystemErrorCode systemErrorCode) {
		this.systemErrorCode = systemErrorCode;
	}

}
